<template>
    <div class="container">
      <SideMenu />
      <div class="main-content">
        <div class="header-bar">
          <div class="topic-header">
            <div class="title-row">
              <div class="favorite-button" @click="handleFavorite">
                <img :src="getFavoriteIcon(isFavor)" class="favorite-icon" alt="favorite" />
              </div>
              <h1 class="topic-title">{{ subject?.matter || '加载中...' }}</h1>
            </div>
            <span class="topic-date">{{ date }}</span>
          </div>
        </div>

        <div class="history-panel" :class="{ 'active': showHistory }">
          <div class="history-header">
            <h3>历史对话</h3>
            <button @click="closeHistory" class="close-btn">×</button>
          </div>
          <div class="history-content">
            <div v-if="loadingHistory" class="loading-history">加载中...</div>
            <div v-else-if="todayHistory.length === 0 && weeklyHistory.length === 0 && olderHistory.length === 0" class="empty-history">暂无历史对话</div>
            
            <!-- 今天的对话 -->
            <div class="history-section">
              <div class="history-section-title">今天</div>
              <div v-if="todayHistory.length === 0" class="empty-section">
                暂无今天的对话
              </div>
              <div v-for="(item, index) in todayHistory" :key="'today-'+index" class="history-item" @click="selectHistoryItem(item)">
                <div class="history-item-title">{{ item.content || '无标题对话' }}</div>
                <div class="history-item-time">{{ formatTime(item.createTime) }}</div>
              </div>
            </div>
            
            <!-- 本周的对话 -->
            <div class="history-section">
              <div class="history-section-title">本周</div>
              <div v-if="weeklyHistory.length === 0" class="empty-section">
                暂无本周的对话
              </div>
              <div v-for="(item, index) in weeklyHistory" :key="'week-'+index" class="history-item" @click="selectHistoryItem(item)">
                <div class="history-item-title">{{ item.content || '无标题对话' }}</div>
                <div class="history-item-time">{{ formatTime(item.createTime) }}</div>
              </div>
            </div>
            
            <!-- 更早的对话 -->
            <div class="history-section">
              <div class="history-section-title">更早</div>
              <div v-if="olderHistory.length === 0" class="empty-section">
                暂无更早的对话
              </div>
              <div v-for="(item, index) in olderHistory" :key="'older-'+index" class="history-item" @click="selectHistoryItem(item)">
                <div class="history-item-title">{{ item.content || '无标题对话' }}</div>
                <div class="history-item-time">{{ formatTime(item.createTime) }}</div>
              </div>
            </div>
          </div>
        </div>
  
        <!-- 主题列表 -->
        <div class="topic-list-container">
          <div class="topic-list">
            <div
              v-for="(item, index) in currentPageTopics"
              :key="index"
              class="topic-item"
              :title = "item.primary?.summary"
              @click="handleTopicItemClick(item)"
            >
              {{ item.primary?.title || '加载中...' }}
            </div>
          </div>
        </div>
  
        <!-- 底部输入框 -->
        <div class="input-container">
          <div class="input-wrapper">
            <unified-input-bar
              :isBlocking="false"
              :isVoiceMode="showVoiceInput"
              :showRagMode="false"
              :showHistory="true"
              :artifacts="virtualArtifacts"
              :selectedArtifact="selectedArtifact"
              @send="handleSend"
              @voice-result="handleVoiceResult"
              @toggle-mode="showVoiceInput = !showVoiceInput"
              @stop-all="handleStopAll"
              @select-artifact="handleSelectArtifact"
              @history-click="handleHistoryClick"
            />
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, computed, onMounted } from 'vue'
  import { useUserStore } from '@/store/user'
  import { ListTopics,SetFavorSubject } from '@/api/subject'
  import UnifiedInputBar from '@/components/UnifiedInputBar.vue'
  import {GetSubjectRequest, ListTopicsResponse, Subject} from '@/types/proto/api/v1/subject_service'
  import {TopicDef} from '@/types/proto/common/common'
  import { useRouter,useRoute } from 'vue-router'
  import SideMenu from '@/components/SideMenu.vue'
  import favorActiveIcon from '@/assets/icon/favor-active.png'
  import favorDeActiveIcon from '@/assets/icon/favor-deactive.png'
  import { ElMessage } from 'element-plus'
  import { GetSubject } from '@/api/subject'
  import { User } from '@/types/proto/api/v1/user_service'
  import { ListUsers } from '@/api/user'
  import {ListKnots} from '@/api/knot'
  import {isToday, isThisWeek, formatTime} from '@/utils/time_utils'
  import { CreateKnotRequest, CreateKnotChatRequest, Knot,DeleteKnotRequest, ListKnotExchangesRequest, ListKnotsRequest } from '@/types/proto/api/v1/knot_service';
  defineOptions({
    name: 'TopicView',
    components: {
      'unified-input-bar': UnifiedInputBar,
      'side-menu': SideMenu
    }
  })

  // ... 保留原有的状态定义 ...
  const router = useRouter()
  const userStore = useUserStore()

  // 新增topics相关逻辑
  const pageSize = 10
  const isFavor = ref(false)
  const subject = ref<Subject | null>(null)
  
  const showVoiceInput = ref(true)
  const date = ref('')
  const newsTotal = ref(0)
  const showHistory = ref(false);
  const loadingHistory = ref(false);
  const todayHistory = ref<Knot[]>([])
  const weeklyHistory = ref<Knot[]>([])
  const olderHistory = ref<Knot[]>([])
  
  const topics = ref<TopicDef[]>([])
  const currentPageTopics = computed(() => {
    return topics.value
  })

  const responders = ref<User[]>([])
  const selectedArtifact =ref<string>('')

  const virtualArtifacts = computed(() => responders.value.map(user => ({
    name: user.nickname || user.username,
    urn: user.urn
  })))

  const closeHistory = () => {
    showHistory.value = false;
  };

  const selectHistoryItem = async (knot: Knot) => {
    console.log('选择历史对话:', knot);
    console.log('plavv knot history vue Item clicked:', knot);
    let query = {content:"", history:knot.urn, subject:subject.value?.urn, responder:selectedArtifact.value}
    router.push({path: '/say', query: query})
  };

  const loadKnotHistory = async () => {
    try {  
        console.log("loadKnots")
        if (userStore.userInfo == null || userStore.userInfo === undefined) {
            console.log("userinfo is null")
            return
        }
        const creatorFilter = `creator == "${userStore.userInfo.urn}" && subject == "${subject.value?.urn}"`
        // 增加pageSize以获取更多历史记录
        const response = await ListKnots({pageSize:50, filter:creatorFilter, pageToken:{limit:50, offset:0}}) 
        console.log(response)
        // 清空历史数组
        todayHistory.value = []
        weeklyHistory.value = []
        olderHistory.value = []

        response.Knots.forEach((knot: Knot) => {
            const knotDate = knot.createTime
            // 提取第一行作为标题
            let content = knot.content
            if (content) {
              // 提取第一行非空内容作为标题
              const lines = content.split('\n').filter(line => line.trim().length > 0)
              if (lines.length > 0) {
                content = lines[0].trim()
                // 限制标题长度
                if (content.length > 20) {
                  content = content.substring(0, 20) + '...'
                }
              } else {
                content = '无标题对话'
              }
              // 更新显示内容
              knot.content = content
            }
            
            if (knotDate) {
              if (isToday(knotDate)) {
                todayHistory.value.push(knot)
              } else if (isThisWeek(knotDate)) {
                weeklyHistory.value.push(knot)
              } else {
                olderHistory.value.push(knot)
              }
            }
        })
        
        // 按时间降序排序
        todayHistory.value.sort((a, b) => 
          new Date(b.createTime || 0).getTime() - new Date(a.createTime || 0).getTime()
        )
        weeklyHistory.value.sort((a, b) => 
          new Date(b.createTime || 0).getTime() - new Date(a.createTime || 0).getTime()
        )
        olderHistory.value.sort((a, b) => 
          new Date(b.createTime || 0).getTime() - new Date(a.createTime || 0).getTime()
        )
    } catch (error) {
      console.error('gRPC request failed:', error);
    }
  }
  // 添加历史按钮点击处理函数
  const handleHistoryClick = async () => {
    // 如果已经显示历史，则关闭它
    if (showHistory.value) {
      showHistory.value = false;
      return;
    }

    try {
      showHistory.value = true;
      loadingHistory.value = true;
      console.log('正在获取历史对话...');
      
      // 获取历史对话数据
      await loadKnotHistory();
      
      loadingHistory.value = false;
    } catch (error) {
      console.error('获取历史对话失败:', error);
      loadingHistory.value = false;
      ElMessage.error('获取历史对话失败');
    }
  }


  const handleStopAll = () => {
		// showVoiceInput.value = false
  }

  const handleSelectArtifact = (urn: string) => {
    console.log('选择的虚拟人:', urn);
    selectedArtifact.value = urn
    // 处理选择的虚拟人
  };

  const handleVoiceResult = (result: string) => {
      handleSend(result,true)
  }
  // 获取收藏图标
  const getFavoriteIcon = (isFavorited: boolean) => {
    return isFavorited ? favorActiveIcon : favorDeActiveIcon
  }

  const updateDate = () => {
    const now = new Date()
    const month = now.getMonth() + 1
    const day = String(now.getDate()).padStart(2, '0')
    const weekdayNames = ['日', '一', '二', '三', '四', '五', '六']
    const weekdayIndex = now.getDay()
    date.value = `${month}.${day} ${weekdayNames[weekdayIndex]}`
  }

  const handleFavorite = async () => {
    try {
      console.log('handleFavorite topicCard')
      let setValue = isFavor.value ? false : true
      if (! subject.value) {
        console.log('subject.value is null')
        return
      }

      const response = await SetFavorSubject({ urn: subject.value?.urn, isFavor: setValue })
      console.log('handleFavorite topicCard', response)
      isFavor.value = response.isFavor
    } catch (error) {
    }
  }

  const handleTopicItemClick = (item: TopicDef) => {
	  console.log('plavv topic vue Item clicked:', item);
    let query = {content:"", topic:item.primary?.urn, subject:subject.value?.urn, responder:selectedArtifact.value}
    userStore.topic = item
    router.push({path: '/say', query: query})
  };


  const handleSend = (message: string,isVoice: boolean = false) => {
	  console.log('plavv topic vue Item in topic.vue clicked sendmessage:', message);
    let query = {"content": message, subject:subject.value?.urn,  responder:selectedArtifact.value} as any
    // if (subject.value) {
    //   const subjectBytes = Subject.encode(subject.value).finish()
    //   const encodedSubject = btoa(Array.from(new Uint8Array(subjectBytes))
    //     .map(byte => String.fromCharCode(byte))
    //     .join(''))
    //   query = {...query, subject: encodedSubject}
    // }
    router.push({path: '/say', query: query})
  };
  
  // 获取主题列表
  const fetchTopics = async () => {
    console.log("fetch topic for subject:", subject.value)
    if (!subject.value) {
      return
    }
    const pageToken = { limit: pageSize, offset: 0 }
    ListTopics({
        subjectUrn: subject.value.urn,
        pageSize,
        pageToken,
        filter: ''
    }).then((res:ListTopicsResponse) => {
        newsTotal.value = res.totalSize
        res.topics.map((topic:TopicDef) => (topics.value.push(topic)))
    })
  }
  
  const route = useRoute()
  // ... 其他原有的方法保持不变 ...
  const parseSubjectFromRoute = () => {
    try {
        const subjectParam = route.query.subject
        if (typeof subjectParam === 'string') {
            const decodedSubject = atob(subjectParam)
            const uint8Array = new Uint8Array(decodedSubject.split('').map(c => c.charCodeAt(0)))
            const decodedData = Subject.decode(uint8Array)
            subject.value = decodedData
            isFavor.value = decodedData.isFavor || false
            fetchTopics()
        }
    } catch (error) {
        console.error('Error parsing topic from route:', error)
    }
  }

  const parseParamFromRoute = async () => {
    try {
        console.log("parse param")
        const subjectUrn = route.query.subject
        let reloadSubject=true
        console.log("subject urn:", subjectUrn)
        if (subjectUrn !==null && typeof subjectUrn === 'string') {
            console.log("subject value1:", subject.value)
            if (subject.value != null) {
              if (subject.value.urn === subjectUrn) {
                console.log("no need to reload")

                reloadSubject = false
              }
            }
        }

        const pageToken = { limit: 1000, offset: 0 }
        const filter = `role == 'AI_ASSISTANT'`
        let us = await ListUsers({ pageSize: 1000, pageToken, filter: filter })
        responders.value = us.users

        if (reloadSubject) {
          let req = {urn:subjectUrn} as GetSubjectRequest
          subject.value = await GetSubject(req)
        }

        if (subject.value != null) {
          isFavor.value = subject.value.isFavor || false
          selectedArtifact.value = subject.value.defaultResponder || ''
          console.log("selectedArtifact:", selectedArtifact.value)
        }

        fetchTopics()
        
    } catch (error) {
        console.error('Error parsing topic from route:', error)
    }
  }
  onMounted(() => {
    console.log("topic on mounted")
    if (!userStore.token) {
      ElMessage.warning('请先登录')
      router.push('/signin')
      return
    }

    if (userStore.subject != null) {
      subject.value = userStore.subject
      isFavor.value = subject.value.isFavor || false
    }
    parseParamFromRoute()
    // parseSubjectFromRoute()
  })
  </script>
  
  <style lang="scss" scoped>
  .container  {
    display: flex;
    height: 100vh;
    width: 100%;
    overflow: hidden;
  }
  .history-panel {
    width: 0;
    height: 100vh;
    background-color: #fff;
    border-right: 1px solid #EAECF0;
    overflow: hidden;
    transition: width 0.3s ease;
    position: fixed;
    right: 0;
    top: 0;
    z-index: 100;
    
    &.active {
      width: 280px;
      overflow-y: auto;
    }
  }

  .history-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid #EAECF0;
    white-space: nowrap;
    
    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 500;
    }
    
    .close-btn {
      background: none;
      border: none;
      font-size: 20px;
      cursor: pointer;
      color: #8E8E93;
      
      &:hover {
        color: #1C1C1E;
      }
    }
  }

  /* 历史内容区域 */
  .history-content {
    padding: 0;
    min-width: 280px;
  }

  /* 历史项目 */
  .history-item {
    padding: 12px 16px;
    cursor: pointer;
    border-bottom: 1px solid #F2F2F7;
    white-space: nowrap;
    
    &:hover {
      background-color: #F7F7F8;
    }
    
    .history-item-title {
      font-size: 14px;
      margin-bottom: 4px;
      color: #1C1C1E;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    
    .history-item-time {
      font-size: 12px;
      color: #8E8E93;
    }
  }

  .loading-history, .empty-history {
    padding: 16px;
    text-align: center;
    color: #8E8E93;
    font-size: 14px;
    white-space: nowrap;
  }
  
  .main-content {
    flex: 1;
    margin-left: 200px;
    display: flex;
    flex-direction: column;
    transition: margin-left 0.3s ease;
    position: relative;
    height: 100vh;
    overflow: hidden;
  }
  
  .header-bar {
    display: flex;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid var(--border-color);
  }

  .topic-list-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
    padding: 20px;
    height: calc(100vh - 180px); // Adjust for header and input container
  }
  
  .topic-list {
    width: 100%;
    max-width: 700px;
    margin: 0 auto;
  }
  
  .topic-item {
    padding: 12px 16px;
    margin-bottom: 8px;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.2s;
    text-align: left;
    background-color: #fff;
    
    &:hover {
      background-color: var(--hover-bg-color);
    }
  }
  
  .input-container {
    width: 100%;
    padding: 16px;
    border-top: 1px solid var(--border-color);
    display: flex;
    justify-content: center;
    background-color: #fff;
    position: relative;
    z-index: 1;
  }
  
  .input-wrapper {
    width: 100%;
    max-width: 800px;
    margin: 0 auto;
    padding: 0 16px;
    
    @media screen and (max-width: 768px) {
      padding: 0 8px;
    }
  }
  
  .topic-header {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
  }
  
  .title-row {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 12px;
  }
  
  .topic-title {
    font-size: 1.5rem;
    margin: 0;
  }
  
  .favorite-button {
    cursor: pointer;
    display: flex;
    align-items: center;
  }
  
  .favorite-icon {
    width: 24px;
    height: 24px;
  }
  
  .topic-date {
    margin-top: 8px;
  }
  </style>